﻿
Imports System.Security.Claims
Imports i_InvoiceApi.Authorization
Imports Microsoft.AspNet.Identity.EntityFramework
Imports Microsoft.Owin.Security
Imports System.Threading.Tasks
Imports Microsoft.Owin.Security.OAuth


Public Class SimpleAuthorizationServerProvider
    Inherits OAuthAuthorizationServerProvider


    Public Overrides Function ValidateClientAuthentication(context As OAuthValidateClientAuthenticationContext) As Task
        ' Resource owner password credentials does not provide a client ID.
        If context.ClientId Is Nothing Then
            context.Validated()
            Return Task.FromResult(Of Object)(Nothing)
        End If
        Return Nothing
    End Function

    Public Overrides Async Function GrantResourceOwnerCredentials(context As OAuthGrantResourceOwnerCredentialsContext) As Task

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", {"*"})

        Using _repo As New AuthRepository()
            Dim user As IdentityUser = Await _repo.FindUser(context.UserName, context.Password)

            If user Is Nothing Then
                context.SetError("invalid_grant", "The user name or password is incorrect.")
                Return
            End If
        End Using

        Dim identity = New ClaimsIdentity(context.Options.AuthenticationType)
        identity.AddClaim(New Claim("sub", context.UserName))
        identity.AddClaim(New Claim("role", "user"))

        context.Validated(identity)

    End Function

End Class